<?php
class PostsController extends AppController {

	var $name = 'Posts';
	var $helpers = array('Tree');
	var $components = array('Site');

	function index() {
		if ($this->params['webservices'] == 'Rss') {
      $fields=array('Post.id','Post.title','Post.content','Post.created','Category.name','Category.description','User.login','User.name');
			$this->set('posts', $this->Post->findAll("Post.replies=0",$fields,"Post.created DESC",10,null,0));
			$this->pageTitle='New topics';
			$this->render();
			exit;
		}
		list($sort,$order)=$this->Site->getSort('modified');
		$count=$this->Post->findCount();
    $fields=array('Post.id','Post.title','Post.replies','Post.modified','Post.points','Post.rated','Post.closed','Category.name','Category.description','User.login','User.name');
		$this->set('posts', $this->Post->findAll(null,$fields,$sort." ".$order,PAGESIZE,$this->pager($count,PAGESIZE),0));

	}

	function view($id = null) {
  	Configure::load('settings');
		vendor('filter');
		$comshow= ($this->luser) ? $this->luser['threshold'] : Configure::read('threshold');

		$this->Post->unbindModel(array('hasMany'=>array('Comment','Vote')));
		$fields="Post.id,Post.title,Post.content,Post.replies,Post.closed,Post.voted,Post.created,Post.points,Post.rated,Category.id,Category.name,Category.description,Category.count,User.id,User.login,User.name,User.vote,User.avatar";
		$p=$this->Post->read($fields, $id);
    if(!$p) {
			$this->Session->setFlash('There is no such topic.','msgerror');
			$this->redirect('/groups/');
			exit;
		}
		$p['Post']['content']=formatpost($p['Post']['content']);

		if($p['Post']['replies']>1) {
			$lastcom=$this->Post->Comment->find("Comment.post_id=".$id,"Comment.id","Comment.created DESC",-1);
			$this->set('lastcom', $lastcom['Comment']['id']);
		}

		if($p['Post']['points']>0)
			$rating=$p['Post']['points']/$p['Post']['rated'];
		else
			$rating=0;
		$this->set('rating', $rating);

		if($this->luser) {

      if($p['User']['id']==$this->luser['id']) {
				$this->set('mypost', true);

				if(Configure::read('canclose') && Configure::read('canclosecom')<=$p['Post']['replies'] && !$p['Post']['closed']) {
					$canclose=1;
				} elseif (Configure::read('canclose') && $p['Post']['closed']) {
					$canclose=2;
				} else {
					$canclose=0;
				}
				$this->set('canclose', $canclose); // user can close comments
			}

      if($p['Post']['voted'] && $p['User']['id']!=$this->luser['id']) $this->set('canrate', true);

			// logged user's bookmarks
	    if ($this->Post->User->Bookmark->findCount("Bookmark.user_id=".$this->luser['id']." AND Bookmark.post_id=".$p['Post']['id'])) // current post in bookmarks?
				$this->set('inb', true);
			else
				$this->set('inb', false);

			// logged user's votes
			$uservotes=$this->Post->Vote->generateList("Vote.user_id={$this->luser['id']} AND Vote.post_id={$p['Post']['id']} AND Vote.comment_id>0", null, null, '{n}.Vote.comment_id', '{n}.Vote.comment_id');
			$this->set('uservotes', $uservotes);
			// users voted
			$showusersvoted=Configure::read('usersvoted'); // show users voted or not
			if($showusersvoted['show']) {
				$usersvoted=$this->Post->Vote->findAll("Vote.post_id={$p['Post']['id']} AND Vote.comment_id>0","DISTINCT Vote.user_id",null,null,null,0);
				if (count($usersvoted) >= $showusersvoted['count']) {
					foreach($usersvoted as $uv) $uvids[]=$uv['Vote']['user_id'];
					$usersvoted=$this->Post->User->findAll(array('User.id'=>$uvids),array("User.login","User.name"),"User.login ASC",null,null,0);
					$this->set('usersvoted', $usersvoted);
				}
			}
		} else {
			$this->set('uservotes', null);
		}

		$fields=array('IF(Comment.vote<'.$comshow.',"-",Comment.text) AS text','Comment.id','Comment.parent_id','Comment.post_id','Comment.user_id','Comment.vote','Comment.created','Comment.del','User.id','User.login','User.name','User.vote','User.avatar');
		$cond=array('Comment.post_id'=>$p['Post']['id']);
    if(isset($this->params['url']['reply']) && $this->luser && !$p['Post']['closed']) {
    		$cid=(int)$this->params['url']['reply'];				
				if($cid>0) {
					$cond['Comment.id']=$cid;
					$commentstree=$this->Post->Comment->findAll($cond, $fields, 'Comment.created DESC',1,1,0);
				}
				if(!empty($commentstree)) $this->set('reply', $cid);
				else $this->set('reply', 0);
		}
		elseif($this->luser && $this->luser['thread']) {
			$this->Post->Comment->recursive=0;
			$commentstree=$this->Post->Comment->findAllThreaded($cond, $fields, 'Comment.created ASC');
		} else {
      $count=$p['Post']['replies'];
			$commentstree=$this->Post->Comment->findAll($cond, $fields, 'Comment.created DESC',PAGESIZECOMMENTS,$this->pager($count,PAGESIZECOMMENTS),0);
		}
		if(isset($commentstree)) $this->set('comments', $commentstree);
		$this->set('post', $p);
	}

	function add($cat = null) {
		$this->checkSession();
    if(!$cat) {
			$this->redirect('/groups/');
			exit;
		}
		$this->Post->Category->recursive=0;
    $category=$this->Post->Category->findByName($cat);
		if ($category['Category']['name']==$cat && $category['Category']['type']==1)
			$this->set('category', $category);
		else {
			$this->redirect('/groups/'); exit;
		}

		if(empty($this->data)) {

			if($category['Category']['cost']<0) { // check for enough points
				$this->Post->User->recursive=-1;
				$cuv=$this->Post->User->read("User.vote",$this->luser['id']);
				if (($cuv['User']['vote']+$category['Category']['cost']) < 0) {
		    	$this->Session->setFlash('Not enough points ('.$cuv['User']['vote'].').','msgerror');
					$this->redirect('/group/'.$cat.'/');
					exit;
				}
			}

			$this->render();
		} else {
			if($this->luser['type']==1 && $category['Category']['type']!=1) {
        $this->redirect('/groups/');
				exit;
			}
			$this->cleanUpFields();

      if (!empty ($this->data['Post']['Tags']))
			{
				$this->data['Tag']['Tag'] = $this->Post->Tag->parseTags($this->data['Post']['Tags']);
			}

			$this->data['Post']['user_id']=$this->luser['id'];
			$this->Post->id="";

			if($this->Post->save($this->data)) {
				$this->Post->Category->inc($this->data['Post']['category_id'],'count',1);
				$this->Post->User->inc($this->data['Post']['user_id'],'postcount',1);
				if($category['Category']['cost']!=0) {
					$this->Post->User->inc($this->data['Post']['user_id'],'vote',$category['Category']['cost']);
				}
				$this->Session->setFlash('Topic created.');
				$this->redirect('/topic/'.$this->Post->getLastInsertId().'.html');
        //$this->flash('Topic created!', '/topic/'.$this->Post->getLastInsertId().'.html');
			} else {
				$this->Session->setFlash('Fill required fields.','msgerror');
				if(empty($this->data['Tag']['Tag'])) { $this->data['Tag']['Tag'] = null; }
			}
		}
	}

	function edit($id) {
  	$this->checkSession();

		if(empty($this->data)) {
			if(!$id) {
				$this->Session->setFlash('There is no such topic.','msgerror');
				$this->redirect('/');
				exit;
			}
			$this->Post->unbindModel(array('hasMany' => array('Comment','Vote')));
			$this->data = $this->Post->read(null, $id);
			if($this->data['Post']['user_id'] != $this->luser['id']) {
				$this->redirect('/');
				exit;
			}
			vendor("filter");
			$this->data['Post']['content']=makecode($this->data['Post']['content'],false);

			if(empty($this->data['Tag'])) { $this->data['Tag'] = null; }

			else

			if (count($this->data['Tag']))
			{
				$tags = '';
				foreach ($this->data['Tag'] as $tag)
				{
					$tags .= $tag['tag'] . ",";
				}
				$this->data['Post']['Tags'] = substr($tags, 0, -1);
			}

		} else {

			$ep=$this->Post->find("Post.id=$id","Post.user_id,Post.modified", null, -1);
      if($ep['Post']['user_id'] != $this->luser['id']) {
				$this->redirect('/');
				exit;
			}

			if(isset($this->data['Post']['closed']))
				$this->data['Post']['modified']=$ep['Post']['modified'];

      if (!empty ($this->data['Post']['Tags']))
			{
				$this->data['Tag']['Tag'] = $this->Post->Tag->parseTags($this->data['Post']['Tags']);
			} else {
				$this->data['Tag']['Tag']=""; // TODO: warning!
			}
			$this->data['Post']['user_id'] = $this->luser['id'];
			if($this->Post->save($this->data)) {
				$this->Session->setFlash('Topic saved.');
				$this->redirect('/topic/'.$this->data['Post']['id'].'.html');
				//$this->flash('Topic saved!', '/topic/'.$this->data['Post']['id'].'.html');
			} else {
				$this->Session->setFlash('Fill required fields.','msgerror');
				if(empty($this->data['Tag']['Tag'])) { $this->data['Tag']['Tag'] = null; }
			}
		}
	}

	function preview() {
		$this->layout="ajax";
    if(empty($this->data['Post']['content'])) {
			exit;
		}
		vendor("filter");
		$content= formatpost(filterpost(trim($this->data['Post']['content'])));
		$posttitle= strip_tags(trim($this->data['Post']['title']));
		$this->set('content',$content);
		$this->set('posttitle',$posttitle);
	}

	function date($y=null,$m=null,$d=null) {
		if(!$y && !$m && !$d) { // archive all
			$pya=$this->Post->findAll(null,array("DISTINCT YEAR(Post.created) AS postyear"),"postyear DESC",null,null,-1);
			foreach($pya as $py) {
				$pma[$py[0]['postyear']]=$this->Post->findAll("Post.created LIKE '".$py[0]['postyear']."%'",array("DISTINCT MONTH(Post.created) AS postmonth"),"postmonth ASC",null,null,-1);
			}
	$this->set("postyears",$pma);
	}

    if($y && $m && !$d) { // archive month
			$this->Site->getCalendar($y,$m);
			$this->set("y",(int)$y);
			$this->set("m",(int)$m);
			$date=$y."-".sprintf("%02d",$m)."-02";
			$this->set("date",$date);
		}
		if($d) {
			$date=$y."-".sprintf("%02d",$m)."-".sprintf("%02d",$d);
			$cond="Post.created LIKE '".$date."%'";
			list($sort,$order)=$this->Site->getSort('modified');
      $count=$this->Post->findCount($cond);
			$fields=array('Post.id','Post.title','Post.replies','Post.closed','Post.created','Post.points','Post.rated','Post.modified','Category.name','Category.description','User.login','User.name');
			$posts=$this->Post->findAll($cond,$fields,$sort." ".$order,PAGESIZE,$this->pager($count,PAGESIZE),0);
			$this->set("posts",$posts);
			$this->set("count",$count);
			$this->set("date",$date);
		}

	}


	function admin_index() {
		$this->checkAdmin(); $this->layout='admin';
		$this->Post->recursive = 0;
    $count=$this->Post->findCount();
		list($sort,$order)=$this->Site->getSort('created');
		$this->set('count',$count);
		$this->set('posts', $this->Post->findAll(null,null,$sort." ".$order,APAGESIZE,$this->pager($count,APAGESIZE),0));
	}

	function admin_delete($id = null) {
		$this->checkAdmin(); $this->layout='admin';
		$this->checkSession();
		if(!$id) {
			$this->redirect('/admin/posts/');
			exit;
		}
		$this->Post->recursive=0;
		$p=$this->Post->read(null, $id);
		if($this->Post->del($id)) {
			$this->Post->User->Bookmark->delByPost($id);
			$this->Post->Category->inc($p['Post']['category_id'],'count',-1);
			$this->Post->User->inc($p['Post']['user_id'],'postcount',-1);
			if($p['Category']['cost']!=0) {
				$this->Post->User->inc($p['Post']['user_id'],'vote',-$p['Category']['cost']);
			}
			if($p['Post']['replies']>0) {
				$this->Post->Comment->delByPost($p['Post']['id']);
				$this->Post->Comment->fixCounts();
			}
			$this->Session->setFlash('Topic deleted: id '.$id.'');
			$this->redirect('/admin/posts/');
		}
	}

	function admin_add() {
		$this->checkAdmin(); $this->layout='admin';
		if(empty($this->data)) {
			$this->set('categories', $this->Post->Category->generateList());
			$this->render();
		} else {
			$this->cleanUpFields();
      if (!empty ($this->data['Post']['Tags']))
			{
				$this->data['Tag']['Tag'] = $this->Post->Tag->parseTags($this->data['Post']['Tags']);
			}

			$this->data['Post']['user_id']=$this->luser['id'];
			if($this->Post->save($this->data)) {
        $this->Post->Category->inc($this->data['Post']['category_id'],'count',1);
				$this->Post->User->inc($this->data['Post']['user_id'],'postcount',1);
				$this->Session->setFlash('Topic created.');
				$this->redirect('/admin/posts/');
			} else {
				$this->Session->setFlash('Fix errors.',"msgerror");
				if(empty($this->data['Tag']['Tag'])) { $this->data['Tag']['Tag'] = null; }
				$this->set('categories', $this->Post->Category->generateList());
			}
		}
	}

	function admin_edit($id = null) {
		$this->checkAdmin(); $this->layout='admin';
		if(empty($this->data)) {
			if(!$id) {
				$this->redirect('/admin/posts/');
				exit;
			}
			$this->Post->unbindModel(array('hasMany' => array('Comment','Vote')));
			$this->data = $this->Post->read(null, $id);

      vendor("filter");
			$this->data['Post']['content']=makecode($this->data['Post']['content'],false);

      if(empty($this->data['Tag'])) { $this->data['Tag'] = null; }

			else

			if (count($this->data['Tag']))
			{
				$tags = '';
				foreach ($this->data['Tag'] as $tag)
				{
					$tags .= $tag['tag'] . ",";
				}
				$this->data['Post']['Tags'] = substr($tags, 0, -1);
			}
			$this->set('categories', $this->Post->Category->generateList());
		} else {
			$this->cleanUpFields();
      if (!empty ($this->data['Post']['Tags']))
			{
				$this->data['Tag']['Tag'] = $this->Post->Tag->parseTags($this->data['Post']['Tags']);
			}

			if($this->Post->save($this->data)) {
				if($this->data['Post']['oldcatid']!=$this->data['Post']['category_id']) {
				$this->Post->Category->inc($this->data['Post']['oldcatid'],'count',-1);
				$this->Post->Category->inc($this->data['Post']['category_id'],'count',1);
				$oldcost=$this->Post->Category->field('cost','Category.id='.$this->data['Post']['oldcatid']);
				$newcost=$this->Post->Category->field('cost','Category.id='.$this->data['Post']['category_id']);
				$oldcost=$oldcost*-1;
				$this->Post->User->inc($this->data['Post']['user_id'],'vote', $oldcost+$newcost);
				}
				$this->Session->setFlash('Topic saved.');
				$this->redirect('/admin/posts/');
			} else {
				$this->Session->setFlash('Fix errors.',"msgerror");
				if(empty($this->data['Tag']['Tag'])) { $this->data['Tag']['Tag'] = null; }
				$this->set('categories', $this->Post->Category->generateList());
			}
		}
	}

}
?>